package cn.wolfcode.crm.web.interceptor;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.util.RequiredPermission;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class CheckPermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取当前登录用户
        //Employee employee = (Employee) request.getSession().getAttribute("EMPLOYEE_IN_SESSION");
        Employee employee = UserContext.getCurrentEmployee();
        //是管理员直接放行
        if (employee.isAdmin()) {
            return true;
        }
        //不是管理员，获取当前要执行的控制器的处理方法
        if (handler instanceof HandlerMethod) {

            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //判断method中是否贴了权限注解@RequiredPermission
            RequiredPermission annotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
            if (annotation == null) {
                //若没有直接放行
                return true;
            }

            //若贴了注解，通过权限注解获取权限表达式
            String expression = annotation.expression();
            //List<String> expressions = permissionService.queryByEmployeeId(employee.getId());
            //从session 中获取员工的缓存起来的权限数据
            //List<String> expressions = (List<String>)request.getSession().getAttribute("EXPRESSIONS_IN_SESSION");
            List<String> expressions = (List<String>) UserContext.getExpression();
            if (expressions.contains(expression)) {
                //用户有这个权限放行
                return true;
            }

            //转发到没权限的提示页面
            request.getRequestDispatcher("/WEB-INF/views/common/nopermission.ftl").forward(request, response);
            //不放行
            return false;
        }
        return true;
    }

}
